前言
UEditor 是由百度开发的富文本web编辑器,是个人除了ckeditor外比较喜欢的一款编辑器。一直喜欢把他用在我的.net项目中,但是在最近做的mvc项目中发现,它与mvc结合得并不是那么完美,它的文件图片上传功能并不能拿来就可以用。接下来就将他内置的方法改造一下,代码很简单,没什么技术含量,大家请轻拍^_^
一、环境介绍
ueditor1.2.3.0asp.net mvc 3二、改写Ueditor上传方法
从官方下载的.net版本中,它是以一般性处理程序来执行文件的上传,管理的。现在我们只需要将net文件夹下的一般处理程序改写成action就OK了!
1、新建一个UploadHelper类,用来执行文件上传
View Code1 ///2 /// UEditor编辑器通用上传类 3 ///4 public class UploadHelper 5 { 6 string _state = "SUCCESS"; 78 string _url; 9 string _currentType; 10 string _uploadpath; 11 string _filename; 12 string _originalName; 13 HttpPostedFileBase _uploadFile; 1415 /** 16* 上传文件的主处理方法 17* @param HttpContext 18* @param string 19* @param string[] 20*@param int 21* @return Hashtable 22*/ 23 public Hashtable UpFile(HttpPostedFileBase file, string pathbase, string[] filetype, int size) 24 { 25 var currUrl = DateTime.Now.ToString("yyyy-MM-dd") + "/"; 26 pathbase = pathbase + currUrl; 2728 _uploadpath = HttpContext.Current.Server.MapPath(pathbase);//获取文件上传路径 2930 try 31 { 32 _uploadFile = file; 33 _originalName = _uploadFile.FileName; 3435 //目录创建 36 CreateFolder(); 3738 //格式验证 39 if (CheckType(filetype)) 40 { 41 _state = "不允许的文件类型"; 42 } 43 //大小验证 44 if (CheckSize(size)) 45 { 46 _state = "文件大小超出网站限制"; 47 } 48 //保存图片 49 if (_state == "SUCCESS") 50 { 51 _filename = ReName(); 52 _uploadFile.SaveAs(_uploadpath + _filename); 53 _url = currUrl + _filename; 54 } 55 } 56 catch (Exception) 57 { 58 _state = "未知错误"; 59 _url = ""; 60 } 61 return GetUploadInfo(); 62 } 6364 /** 65 * 上传涂鸦的主处理方法 66* @param HttpContext 67* @param string 68* @param string[] 69*@param string 70* @return Hashtable 71 */ 72 public Hashtable UpScrawl(HttpPostedFileBase file, string pathbase, string tmppath, string base64Data) 73 { 74 var currUrl = DateTime.Now.ToString("yyyy-MM-dd") + "/"; 75 pathbase = pathbase + currUrl; 76 _uploadpath = HttpContext.Current.Server.MapPath(pathbase);//获取文件上传路径 77 FileStream fs = null; 78 try 79 { 80 //创建目录 81 CreateFolder(); 82 //生成图片 83 _filename = Guid.NewGuid() + ".png"; 84 fs = File.Create(_uploadpath + _filename); 85 byte[] bytes = Convert.FromBase64String(base64Data); 86 fs.Write(bytes, 0, bytes.Length); 8788 _url = currUrl+_filename; 89 } 90 catch (Exception) 91 { 92 _state = "未知错误"; 93 _url = ""; 94 } 95 finally 96 { 97 if (fs != null) fs.Close(); 98 DeleteFolder(HttpContext.Current.Server.MapPath(tmppath)); 99 }100 return GetUploadInfo();101 }102 103 /**104 * 获取文件信息105 * @param context106 * @param string107 * @return string108 */109 public string GetOtherInfo(string field)110 {111 string info = null;112 if (HttpContext.Current.Request.Form[field] != null && !String.IsNullOrEmpty(HttpContext.Current.Request.Form[field]))113 {114 info = field == "fileName" ? HttpContext.Current.Request.Form[field].Split(',')[1] : HttpContext.Current.Request.Form[field];115 }116 return info;117 }118 119 /**120 * 获取上传信息121 * @return Hashtable122 */123 private Hashtable GetUploadInfo()124 {125 var infoList = new Hashtable {{"state", _state}, {"url", _url}};126 127 if (_currentType != null)128 infoList.Add("currentType", _currentType);129 if (_originalName != null)130 infoList.Add("originalName", _originalName);131 return infoList;132 }133 134 /**135 * 重命名文件136 * @return string137 */138 private string ReName()139 {140 return Guid.NewGuid() + GetFileExt();141 }142 143 /**144 * 文件类型检测145 * @return bool146 */147 private bool CheckType(string[] filetype)148 {149 _currentType = GetFileExt();150 return Array.IndexOf(filetype, _currentType) == -1;151 }152 153 /**154 * 文件大小检测155 * @param int156 * @return bool157 */158 private bool CheckSize(int size)159 {160 return _uploadFile.ContentLength >= (size * 1024*1024);161 }162 163 /**164 * 获取文件扩展名165 * @return string166 */167 private string GetFileExt()168 {169 string[] temp = _uploadFile.FileName.Split('.');170 return "." + temp[temp.Length - 1].ToLower();171 }172 173 /**174 * 按照日期自动创建存储文件夹175 */176 private void CreateFolder()177 {178 if (!Directory.Exists(_uploadpath))179 {180 Directory.CreateDirectory(_uploadpath);181 }182 }183 184 /**185 * 删除存储文件夹186 * @param string187 */188 public void DeleteFolder(string path)189 {190 //if (Directory.Exists(path))191 //{192 //Directory.Delete(path, true);193 //}194 }195 }
2、新建一个UEditorController
3、文件上传
View Code1 //文件上传 2 [HttpPost] 3 public JsonResult FileUp() 4 { 5 var file = Request.Files["upfile"]; 6 //上传配置 7 const string pathbase = "/UploadFiles/file/"; //保存路径 8 string[] filetype = { ".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".wmv" };//文件允许格式 9 const int size = 100; //文件大小限制,单位MB,同时在web.config里配置环境默认为100MB10 11 //上传文件12 var up = new UploadHelper();13 Hashtable info = up.UpFile(file, pathbase, filetype, size);14 return Json(new { state = info["state"], url = info["url"], fileType = info["currentType"], original = info["originalName"] });15 }4、图片上传,方法同上
View Code1 //图片上传 2 [HttpPost] 3 public JsonResult ImageUp(HttpPostedFileBase upfile) 4 { 5 //上传配置 6 const string pathbase = "/UploadFiles/img/"; //保存路径 7 const int size = 2; //文件大小限制,单位MB//文件大小限制,单位MB 8 string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };//文件允许格式 9 10 //上传图片11 var up = new UploadHelper();12 Hashtable info = up.UpFile(upfile, pathbase, filetype, size);13 string ti = up.GetOtherInfo("pictitle");//获取图片描述14 string oriName = up.GetOtherInfo("fileName");//获取原始文件名15 return Json(new { url = info["url"], title = ti, original = oriName, state = info["state"] });16 }5、涂鸦功能
View Code1 //涂鸦 2 [HttpPost] 3 public JsonResult ScrawUp(HttpPostedFileBase upfile) 4 { 5 string action = Request.Form["action"]; 67 if (action == "tmpImg") 8 { 9 //上传配置10 const string pathbase = "/UploadFiles/tmp/"; //保存路径11 const int size = 2; //文件大小限制,单位mb//文件大小限制,单位KB12 string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };//文件允许格式13 14 //上传图片15 var up = new UploadHelper();16 Hashtable info = up.UpFile(upfile, pathbase, filetype, size);17 return Json(new { url = info["url"], state = info["state"] });18 //System.Web.HttpContext.Current.Response.Write("parent.ue_callback('" + info["url"] + "','" + info["state"] + "')");//回调函数19 }20 else21 {22 const string pathbase = "/UploadFiles/scraw/"; //保存路径23 const string tmpPath = "/UploadFiles/tmp/"; //临时图片目录24 var content = Request.Form["content"];25 //上传图片26 var up = new UploadHelper();27 var info = up.UpScrawl(upfile, pathbase, tmpPath, content);28 29 //向浏览器返回json数据30 return Json(new { url = info["url"], state = info["state"] });31 }32 }6、图片管理
View Code1 //图片管理 2 [HttpPost] 3 public JsonResult ImageManager() 4 { 5 string path = Server.MapPath("/UploadFiles/");//最好使用缩略图地址,否则当网速慢时可能会造成严重的延时 6 string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };//文件允许格式 78 string act = Server.HtmlEncode(Request["action"]); 9 10 if (act == "get")11 {12 var info = new DirectoryInfo(path);13 var str = GetImages(info, filetype, "");14 return Json(new {data = str == "" ? "" : str.Substring(14)});15 }16 return Json(new {data = ""});17 }18 19 private string GetImages(DirectoryInfo info, string[] filetype,string path)20 {21 string str="";22 if (info.Exists)23 {24 DirectoryInfo[] infoArr = info.GetDirectories();25 foreach (FileInfo fi in info.GetFiles())26 {27 if (Array.IndexOf(filetype, fi.Extension) != -1)28 {29 str += "ue_separate_ue"+path + "/" + fi.Name;30 }31 }32 str = infoArr.Aggregate(str, (current, tmpInfo) => current + GetImages(tmpInfo, filetype,path+"/"+tmpInfo.Name));33 }34 return str;35 }三、修改Ueditor
1、修改editor_config.js文件中文件上传方法和上传路径
将变量URL改为editor的路径 URL = window.UEDITOR_HOME_URL || "/Content/ueditor1_2_3_0/";将window.UEDITOR_CONFIG中的imageUrl,scrawlUrl,fileUrl,catcherUrl,imageManagerUrl改成你相对于的action地址
View Code var fileAddr = "/UploadFiles";/** * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。 */window.UEDITOR_CONFIG = {//为编辑器实例添加一个路径,这个不能被注释UEDITOR_HOME_URL : URL//语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件://lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase()//,lang:"zh-cn"//,langPath:URL +"lang/"//图片上传配置区, imageUrl: "/UAdmin/UEditor/ImageUp"//"net/imageUp.ashx" //图片上传提交地址, imagePath: fileAddr +"/img/"//图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置//,imageFieldName:"upfile"//图片数据的key,若此处修改,需要在后台对应文件修改对应参数//,compressSide:0//等比压缩的基准,确定maxImageSideLength参数的参照对象。0为按照最长边,1为按照宽度,2为按照高度//,maxImageSideLength:900//上传图片最大允许的边长,超过会自动等比缩放,不缩放就设置一个比较大的值,